home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 4.iso / src / exampleCode / viewkit / xcontact / parody / pstrings.c++ < prev    next >
Encoding:
C/C++ Source or Header  |  1994-08-02  |  1.8 KB  |  102 lines

  1. // -------- strings.c++
  2.  
  3. #include "parody.h"
  4.  
  5. // ------- put a string into a pString
  6. void pString::putstr(char *s)
  7. {
  8.     delete sptr;
  9.     length = strlen(s);
  10.     sptr = new char[length+1];
  11.     strcpy(sptr, s);
  12. }
  13.  
  14. // --- convert from char *
  15. pString::pString(char *s)
  16. {
  17.     sptr = NULL;
  18.     putstr(s);
  19. }
  20.  
  21. // ------- copy constructor
  22. pString::pString(pString& s)
  23. {
  24.     sptr = NULL;
  25.     putstr(s.sptr);
  26. }
  27.  
  28. // -------- construct with a size and fill character
  29. pString::pString(int len, char fill)
  30. {
  31.     length = len;
  32.     sptr = new char[length+1];
  33.     memset(sptr, fill, length);
  34.     *(sptr+len) = '\0';
  35. }
  36.  
  37. // -------- assignment
  38. pString& pString::operator=(pString &s)
  39. {
  40.     if (this != &s)
  41.         putstr(s.sptr);
  42.     return *this;
  43. }
  44.  
  45. // ------- concatenation operator (str1 + str2)
  46. pString pString::operator+(pString &s)
  47. {
  48.     pString temp(strlen(s.sptr) + strlen(sptr));
  49.     strcpy(temp.sptr, sptr);
  50.     strcat(temp.sptr, s.sptr);
  51.     return temp;
  52. }
  53.  
  54. // ------ substring: right len chars
  55. pString pString::right(int len)
  56. {
  57.     pString tmp(sptr + strlen(sptr) - len);
  58.     return tmp;
  59. }
  60.  
  61. // ------ substring: left len chars
  62. pString pString::left(int len)
  63. {
  64.     pString tmp(len);
  65.     strncpy(tmp.sptr, sptr, len);
  66.     return tmp;
  67. }
  68.  
  69. // ------ substring: middle len chars starting from where
  70. pString pString::mid(int len, int where)
  71. {
  72.     pString tmp(len);
  73.     if (where < (int) strlen(sptr))
  74.         strncpy(tmp.sptr,sptr+where,len);
  75.     return tmp;
  76. }
  77.  
  78. // ---- find offset to first instance of specified char
  79. int pString::FindChar(unsigned char ch)
  80. {
  81.     char *cp = strchr(sptr, ch);
  82.     if (cp == NULL)
  83.         return -1;
  84.     return (int) (cp - sptr);
  85. }
  86.  
  87. // ------- stream I/O
  88. ostream& operator<< (ostream& os, pString& str)
  89. {
  90.     os << str.sptr;
  91.     return os;
  92. }
  93.  
  94. istream& operator>> (istream& is, pString& str)
  95. {
  96.     *str.sptr = '\0';
  97.     while (*str.sptr == '\0')
  98.         is.getline(str.sptr, str.length+1);
  99.     return is;
  100. }
  101.  
  102.